﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

[RequireComponent(typeof(Cell))]
public class InfectedCell : MonoBehaviour {
	public GameObject Child;//预制体
	[Tooltip("复制的数量")]
    public Vector2Int CopyRange;
    [Tooltip("复制的周期")]
    public int CopyIntervals;

	public float RandomCopyRange = 1f;
    public GameObject burstParticle;

    private int m_CurrentIntervals;

	private UnityAction m_Action;

	private void Awake() {
        m_CurrentIntervals = 0;

		m_Action += Tick;

        GameController.Instance.AddTickEvent(m_Action);
	}
    void Start() {
        transform.localEulerAngles = new Vector3(0, 0, 0);
        gameObject.GetComponent<Cell>().GetRandomDirection(true);
    }
	
	// Update is called once per frame
	void Update () {
        gameObject.GetComponent<Cell>().MoveAway();
	}

	 private void Tick() {
        m_CurrentIntervals ++;
        Debug.Log(m_CurrentIntervals);
        if(m_CurrentIntervals == CopyIntervals) {
            Boom();
        }
    }

    // 破裂
    private void Boom()  {
        GameController.Instance.RemoveTickEvent(m_Action);

        int num = Random.Range(CopyRange.x, CopyRange.y);

        
        GameObject particle = Instantiate(burstParticle, this.transform.position, Quaternion.identity);
        
        particle.transform.localEulerAngles = new Vector3(-90f,0,0);
        
        for(int i = 0; i < num; i++){
            GameObject obj = Instantiate(Child, this.transform.position, Random.rotation);
			float x = Random.Range(-RandomCopyRange / 2, RandomCopyRange / 2);
            float y = Random.Range(-RandomCopyRange / 2, RandomCopyRange / 2);
			obj.transform.position += new Vector3(x, y, 0f);

			obj.transform.rotation = Quaternion.Euler(0f, 0f, Random.Range(0f, 360f));
        }

        //毁灭自己
        Destroy(this.gameObject);
    }
}
